package com.example.schoolexam2.utils;

import cn.hutool.core.util.IdUtil;
import com.example.schoolexam2.entity.QuestionCheckd;
import com.example.schoolexam2.entity.QuestionFill;
import com.example.schoolexam2.entity.QuestionJudge;
import com.example.schoolexam2.entity.QuestionRadio;
import com.example.schoolexam2.vo.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.BeanUtils;

import java.io.FileOutputStream;
import java.util.*;

import static com.example.schoolexam2.service.impl.QuestionServiceImpl.IMgFolder;

public class QuestionAboutUtil {
    //获取数据并调用changeType()转换成字符串 导入试题库相关
    public static void completePacking(Sheet sheet, String type, int row, String[][] pics,
                                       List<QuestionRadio> radios, List<QuestionCheckd> checkds,
                                       List<QuestionFill> fills, List<QuestionJudge> judges,String departmentId) {
        Map<String, String> stringStringMap = judgeHavePic(row, pics);
        String questionName = null;
        String questionA = null;
        String questionB = null;
        String questionC = null;
        String questionD = null;
        if (stringStringMap != null) { //当前行有图片
            Object[] objects = stringStringMap.keySet().toArray(); //将建取出，比对是那一行的图片
            for (int i = 0; i < objects.length; i++) {
                switch (objects[i].toString()) {
                    case "1": //题干有图片
                        questionName = stringStringMap.get(objects[i]);
                        break;
                    case "2": //a选项
                        questionA = stringStringMap.get(objects[i]);
                        break;
                    case "3": //b选项
                        questionB = stringStringMap.get(objects[i]);
                        break;
                    case "4": //c选项
                        questionC = stringStringMap.get(objects[i]);
                        break;
                    case "5":  //d选项有图片
                        questionD = stringStringMap.get(objects[i]);
                        break;
                }
            }

        }
        QuestionUtilsBean questionUtilsBean = new QuestionUtilsBean(questionName, questionA, questionB, questionC, questionD);
        completePackingPub(sheet, type, row, radios, checkds,
                fills, judges, questionUtilsBean,departmentId);
    }


    //将completepacking()会用到的公共代码抽出
    public static void completePackingPub(Sheet sheet, String type, int row,
                                          List<QuestionRadio> radios, List<QuestionCheckd> checkds,
                                          List<QuestionFill> fills, List<QuestionJudge> judges, QuestionUtilsBean bean,String departmentId) {
        if (type.equals("1")) {//单选题
            QuestionRadio questionRadio = new QuestionRadio();
            //封装单选题对象
            questionRadio.setQuestionId(IdUtil.simpleUUID());
            questionRadio.setQuestionName(changeType(sheet, row, 1, bean.getQuestionName()));
            questionRadio.setQuestionA(changeType(sheet, row, 2, bean.getQuestionA()));
            questionRadio.setQuestionB(changeType(sheet, row, 3, bean.getQuestionB()));
            questionRadio.setQuestionC(changeType(sheet, row, 4, bean.getQuestionC()));
            questionRadio.setQuestionD(changeType(sheet, row, 5, bean.getQuestionD()));
            questionRadio.setQuestionAnswer(changeType(sheet, row, 6, null));
            questionRadio.setQuestionDiscribe(changeType(sheet, row, 7, null));
            //获取此试题的公私有信息
            try {
                if (changeType(sheet,row,8,null)=="0"){
                    //将创建试卷的老师的部门id拿到
                    questionRadio.setIsPublic(0);
                    questionRadio.setDepartmentId(departmentId);
                }
            }catch (NullPointerException e){
                //当前格没填数据，表中字段默认是公开，所以可以不处理
            }
            radios.add(questionRadio);
            System.out.println(questionRadio);
        } else if (type.equals("2")) {//多选题
            QuestionCheckd questionCheckd = new QuestionCheckd();
            questionCheckd.setQuestionId(IdUtil.simpleUUID());
            questionCheckd.setQuestionName(changeType(sheet, row, 1, bean.getQuestionName()));
            questionCheckd.setQuestionA(changeType(sheet, row, 2, bean.getQuestionA()));
            questionCheckd.setQuestionB(changeType(sheet, row, 3, bean.getQuestionB()));
            questionCheckd.setQuestionC(changeType(sheet, row, 4, bean.getQuestionC()));
            questionCheckd.setQuestionD(changeType(sheet, row, 5, bean.getQuestionD()));
            questionCheckd.setQuestionAnswer(changeType(sheet, row, 6, null));
            questionCheckd.setQuestionDiscribe(changeType(sheet, row, 7, null));
            try {
                if (changeType(sheet,row,8,null)=="0"){
                    //将创建试卷的老师的部门id拿到
                    questionCheckd.setIsPublic(0);
                    questionCheckd.setDepartmentId(departmentId);
                }
            }catch (NullPointerException e){
                //当前格没填数据，表中字段默认是公开，所以可以不处理
            }
            checkds.add(questionCheckd);
            System.out.println(questionCheckd);
        } else if (type.equals("3")) {//填空题
            QuestionFill questionFill = new QuestionFill();
            questionFill.setQuestionId(IdUtil.simpleUUID());
            questionFill.setQuestionName(changeType(sheet, row, 1, bean.getQuestionName()));
            questionFill.setQuestionAnswer(changeType(sheet, row, 6, null));
            questionFill.setQuestionDiscribe(changeType(sheet, row, 7, null));
            try {
                if (changeType(sheet,row,8,null)=="0"){
                    //将创建试卷的老师的部门id拿到
                    questionFill.setIsPublic(0);
                    questionFill.setTeacherId(departmentId);
                }
            }catch (NullPointerException e){
                //当前格没填数据，表中字段默认是公开，所以可以不处理
            }
            fills.add(questionFill);
            System.out.println(questionFill);
        } else if (type.equals("4")) {//判断题
            QuestionJudge questionJudge = new QuestionJudge();
            questionJudge.setQuestionId(IdUtil.simpleUUID());
            questionJudge.setQuestionName(changeType(sheet, row, 1, bean.getQuestionName()));
            questionJudge.setQuestionAnswer(changeType(sheet, row, 6, null));
            questionJudge.setQuestionDiscribe(changeType(sheet, row, 7, null));
            try {
                if (changeType(sheet,row,8,null)=="0"){
                    //将创建试卷的老师的部门id拿到
                    questionJudge.setIsPublic(0);
                    questionJudge.setDepartmentId(departmentId);
                }
            }catch (NullPointerException e){
                //当前格没填数据，表中字段默认是公开，所以可以不处理
            }
            judges.add(questionJudge);
            System.out.println(questionJudge);
        } else {
            //当前行没有标注题号或者标注错误，此表不保存，返回错误信息
            throw new NullPointerException();
        }
    }

    //将表格数据转化成字符串   导入试题库相关
    public static String changeType(Sheet sheet, int row, int cell, String picAddress) {
        if (sheet instanceof XSSFSheet) {
            XSSFSheet sheet1 = (XSSFSheet) sheet;
            if (picAddress == null) {
                try {//当前格没有图片
                    XSSFCell cell1 = sheet1.getRow(row).getCell(cell);
                    cell1.setCellType(CellType.STRING);
                    return cell1.getStringCellValue();
                } catch (Exception e) {//当前行没填数据
                    throw new NullPointerException();
                }
            }
            try {//当前格存在图片
                XSSFCell cell1 = sheet1.getRow(row).getCell(cell);
                cell1.setCellType(CellType.STRING);
                return cell1.getStringCellValue() + "@_@" + picAddress;
            } catch (NullPointerException e) {//当前行只有图片没有数值
                return "@_|"+picAddress;
            }
        } else if (sheet instanceof HSSFSheet) {
            HSSFSheet sheet2 = (HSSFSheet) sheet;
            if (picAddress == null) {
                try {//当前格没有图片
                    HSSFCell cell1 = sheet2.getRow(row).getCell(cell);
                    cell1.setCellType(CellType.STRING);
                    return cell1.getStringCellValue();
                } catch (Exception e) {//当前行没填数据
                    throw new NullPointerException();
                }
            }
            try {//当前格存在图片
                HSSFCell cell1 = sheet2.getRow(row).getCell(cell);
                cell1.setCellType(CellType.STRING);
                return cell1.getStringCellValue() + "@_@" + picAddress;
            } catch (NullPointerException e) {//当前行只有图片没有数值
                return "@_|"+picAddress;
            }
        }
        return null;
    }

    //找到文件所有图片位置，通过流并调用pic()保存图片   导入试题库相关 Xlsx
    public static Map<String, String> findAllPicture(XSSFSheet sheet) throws Exception {
        //读取出来的excle的图片信息和位置信息存储在该集合中
        Map<String, XSSFPictureData> maplist = new HashMap<String, XSSFPictureData>();
        List<XSSFShape> list = null;
        try {
            list = sheet.getDrawingPatriarch().getShapes();  //这里可能会出错
            for (XSSFShape xssfShape : list) {
                if (xssfShape instanceof XSSFPicture) {
                    XSSFPicture picture = (XSSFPicture) xssfShape;
                    XSSFClientAnchor clientAnchor = picture.getClientAnchor();
                    XSSFPictureData pictureData = picture.getPictureData();
                    //key=行号+列号
                    String key = clientAnchor.getRow1() + "-" + clientAnchor.getCol1();
                    maplist.put(key, pictureData);
                }
            }
            Map<String, String> pic = picXlsx(maplist);
            return pic;
        } catch (NullPointerException e) {
            //当前表没有图片
            return null;
        }
    }

    // 找到文件所有图片位置，通过流并调用pic()保存图片   导入试题库相关 Xls
    public static Map<String, String> findAllPicture(HSSFSheet sheet) throws Exception {
        //读取出来的excle的图片信息和位置信息存储在该集合中
        Map<String, HSSFPictureData> maplist = new HashMap<String, HSSFPictureData>();
        List<HSSFShape> children = null;
        try {
            children = sheet.getDrawingPatriarch().getChildren();//这里可能会出错
            for (HSSFShape shape : children) {
                if (shape instanceof HSSFPicture) {
                    HSSFPicture picture = (HSSFPicture) shape;
                    HSSFClientAnchor anchor = (HSSFClientAnchor) picture.getAnchor();
                    HSSFPictureData pictureData = picture.getPictureData();
                    //key=行号+列号
                    String key = anchor.getRow1() + "-" + anchor.getCol1();
                    maplist.put(key, pictureData);
                }
            }
            Map<String, String> pic = picXls(maplist);
            return pic;
        } catch (NullPointerException e) {
            //当前表没有图片
            return null;
        }

    }

    //通过数据流保存图片数据 返回图片和位置信息的集合   导入试题库相关
    public static Map<String, String> picXlsx(Map<String, XSSFPictureData> maplist) throws Exception {
        //图片保存相关
        Object[] key1 = maplist.keySet().toArray();
        Map<String, String> resultMap = new HashMap<>();
        for (int i = 0; i < maplist.size(); i++) {
            //获取图片流
            XSSFPictureData xssfPictureData = maplist.get(key1[i]);
            //获取图片所在的指定的单元格的数据
//                    String picName = key1[i].toString();
            String picName = IdUtil.simpleUUID();

            resultMap.put(key1[i].toString(), IMgFolder + picName + ".jpg");

            byte[] data = xssfPictureData.getData();
            //图片保存路径
            FileOutputStream out = new FileOutputStream(IMgFolder + picName + ".jpg");
            out.write(data);
            out.close();
        }
        return resultMap;
    }

    public static Map<String, String> picXls(Map<String, HSSFPictureData> maplist) throws Exception {
        //图片保存相关
        Object[] key1 = maplist.keySet().toArray();
        Map<String, String> resultMap = new HashMap<>();
        for (int i = 0; i < maplist.size(); i++) {
            //获取图片流
            HSSFPictureData hssfPictureData = maplist.get(key1[i]);
            //获取图片所在的指定的单元格的数据
//                    String picName = key1[i].toString();
            String picName = IdUtil.simpleUUID();

            resultMap.put(key1[i].toString(), IMgFolder + picName + ".jpg");

            byte[] data = hssfPictureData.getData();
            //图片保存路径
            FileOutputStream out = new FileOutputStream(IMgFolder + picName + ".jpg");
            out.write(data);
            out.close();
        }
        return resultMap;
    }

    //这个方法将pic()返回的集合转化成可用的数组   导入试题库相关
    public static String[][] zhongjian(Map<String, String> allPicture) {
        /**  用一个二维数组承载
         * {
         *     {行数}
         *     {列数}
         *     {图片位置}
         * }
         */
        if (allPicture != null) {
            String[][] arrays = new String[allPicture.size()][allPicture.size()];

            Set<String> strings = allPicture.keySet();
            Object[] objects = allPicture.keySet().toArray();
            Iterator<String> iterator = strings.iterator();
            //用一个String数组接收key集合
            String[] keyTemp = new String[strings.size()];
            int keyi = 0;
            //将keyset转存到String数组中
            while (iterator.hasNext()) {
                keyTemp[keyi] = iterator.next();
                keyi++;
            }
            //通过中间key数组，转存到最终要用的String数组中
            for (int i = 0; i < allPicture.size(); i++) {
                String temp = keyTemp[i];
                String substring = temp.substring(0, 1); //得到行数，添加到arrays中
                arrays[0][i] = substring;
                String substring1 = temp.substring(2);
                arrays[1][i] = substring1;
                arrays[2][i] = allPicture.get(objects[i]);
            }

            //测试要返还的数据是否正确
            for (int a = 0; a < arrays.length; a++) {
                for (int b = 0; b < arrays[1].length; b++) {
                    System.out.print(arrays[a][b] + " ");

                }
                System.out.println("当前行结束");
            }

            return arrays;
        } else {
            return null;
        }
    }

    //判断当前行是否有图片   导入试题库相关
    public static Map<String, String> judgeHavePic(int row, String[][] pics) {
        if (pics != null) {
            List<String> picCell = new ArrayList<>();
            List<String> lieCell = new ArrayList<>();
            for (int b = 0; b < pics[0].length; b++) {
                if (row == Integer.parseInt(pics[0][b])) { //当前行存在图片，但不确定有多少图片
                    lieCell.add(pics[1][b]);
                    picCell.add(pics[2][b]);
                }
            }
            Map<String, String> picAndCell = new HashMap<>();
            if (picCell.size() > 0) { //如果集合长度不为0代表当前行有图片
                for (int i = 0; i < picCell.size(); i++) {
//                picAndCell[0][i]=lieCell.get(i);//存储当前图片的列所在位置
//                picAndCell[1][i]=picCell.get(i); //存储当前图片地址
                    picAndCell.put(lieCell.get(i), picCell.get(i));
                }
                return picAndCell;
            }
            return null;
        } else {
            return null;
        }
    }

    //将问题实体转化成前台需要的形式
    public static TestVO trans(List<QuestionRadio> radios, List<QuestionCheckd> checkds,
                               List<QuestionFill> fills, List<QuestionJudge> judges) {
        TestVO testVO = new TestVO(); //返回的结果集

        //单选
        List<QuestionRadioListVo> allRadioListVo = new ArrayList<>(); //要返回的单选题的集合
        for (QuestionRadio questionRadio : radios) {
            QuestionRadioListVo questionRadioListVo = new QuestionRadioListVo(); //创建一个单独的返回实体
            BeanUtils.copyProperties(questionRadio, questionRadioListVo); //拷贝实体
            String questionA = questionRadio.getQuestionA();
            String questionB = questionRadio.getQuestionB();
            String questionC = questionRadio.getQuestionC();
            String questionD = questionRadio.getQuestionD();
            QuestionOptionListVo[] questionOptionListVos = new QuestionOptionListVo[4]; //选项数组
            questionOptionListVos[0] = new QuestionOptionListVo(questionA, false);
            questionOptionListVos[1] = new QuestionOptionListVo(questionB, false);
            questionOptionListVos[2] = new QuestionOptionListVo(questionC, false);
            questionOptionListVos[3] = new QuestionOptionListVo(questionD, false);
            questionRadioListVo.setOptions(questionOptionListVos);
            allRadioListVo.add(questionRadioListVo);
        }
        List<QuestionCheckdListVo> allCheckdListVo = new ArrayList<>(); //要返回的多选题的集合
        for (QuestionCheckd questionCheckd : checkds) {
            QuestionCheckdListVo questionCheckdListVo = new QuestionCheckdListVo();//创建一个单独的返回实体
            BeanUtils.copyProperties(questionCheckd, questionCheckdListVo); //拷贝实体
            String questionA = questionCheckd.getQuestionA();
            String questionB = questionCheckd.getQuestionB();
            String questionC = questionCheckd.getQuestionC();
            String questionD = questionCheckd.getQuestionD();
            QuestionOptionListVo[] questionOptionListVos = new QuestionOptionListVo[4]; //选项数组
            questionOptionListVos[0] = new QuestionOptionListVo(questionA, false);
            questionOptionListVos[1] = new QuestionOptionListVo(questionB, false);
            questionOptionListVos[2] = new QuestionOptionListVo(questionC, false);
            questionOptionListVos[3] = new QuestionOptionListVo(questionD, false);
            questionCheckdListVo.setOptions(questionOptionListVos);
            allCheckdListVo.add(questionCheckdListVo);
        }
        List<QuestionFillListVo> allFillListVo = new ArrayList<>();//要返回的填空题集合
        for (QuestionFill questionFill : fills) {
            QuestionFillListVo questionFillListVo = new QuestionFillListVo(); //要返回的单独实体
            BeanUtils.copyProperties(questionFill, questionFillListVo); //拷贝实体
//            QuestionOptionListVo[] questionOptionListVos=new QuestionOptionListVo[1];
//            questionOptionListVos[0]=new QuestionOptionListVo(questionFill.getQuestionAnswer(),false);
//            questionFillListVo.setOptions(questionOptionListVos);
            if (questionFillListVo.getQuestionAnswer().contains("-")){//答案有多个
                String questionAnswer = questionFillListVo.getQuestionAnswer();
                String[] split = questionAnswer.split("-");
                QuestionOptionListVo[] questionOptionListVos=new QuestionOptionListVo[split.length];
                for (int i=0;i< split.length;i++){
                    questionOptionListVos[i]=new QuestionOptionListVo(split[i],false);
                }
                questionFillListVo.setOptions(questionOptionListVos);
            }else{ //答案只有一个
                QuestionOptionListVo[] questionOptionListVos = new QuestionOptionListVo[1];
                questionOptionListVos[0] = new QuestionOptionListVo(questionFill.getQuestionAnswer(), false);
                questionFillListVo.setOptions(questionOptionListVos);
            }
            allFillListVo.add(questionFillListVo);
        }
        List<QuestionJudgeListVo> allJudgeListVo = new ArrayList<>();//要返回的判断题集合
        for(QuestionJudge questionJudge: judges){
            QuestionJudgeListVo questionJudgeListVo = new QuestionJudgeListVo();//要返回的单独实体
            BeanUtils.copyProperties(questionJudge,questionJudgeListVo); //拷贝实体

            QuestionOptionListVo[] questionOptionListVos = new QuestionOptionListVo[2];
            questionOptionListVos[0] = new QuestionOptionListVo("对", false);
            questionOptionListVos[1] = new QuestionOptionListVo("错", false);
            questionJudgeListVo.setOptions(questionOptionListVos);
            allJudgeListVo.add(questionJudgeListVo);
        }

        testVO.setRadios(allRadioListVo);
        testVO.setCheckds(allCheckdListVo);
        testVO.setFills(allFillListVo);
        testVO.setJudges(allJudgeListVo);
        return testVO;

    }


}
